import React, { useEffect, useState, useRef } from 'react'
import { Button, Upload, Image, Modal, Layout, Space, message, Table, Input, Popover, Avatar } from 'antd';
import { HeartTwoTone, EditTwoTone, DeleteTwoTone, ExclamationCircleOutlined } from '@ant-design/icons';
import { UploadOutlined, UserAddOutlined } from '@ant-design/icons';
// import GoodsCascader from '../../../components/GoodsCascader'
import { useNavigate } from 'react-router-dom'
import axios from 'axios';
import { screenHeight, screenWidth } from '../../../Constants'
const { confirm } = Modal;
let editGiftInfo = {}
let addGiftInfo = {}
const { Search } = Input;
export default function Index() {
  const navigate = useNavigate()
  const [originData, setOriginData] = useState(0);
  const [giftList, setGiftList] = useState(0);

  const { Content } = Layout;
  const [visible, setVisible] = React.useState(false);
  const [visible2, setVisible2] = React.useState(false);
  const giftNameRef = useRef();
  const giftPriceRef = useRef();
  const giftStockRef = useRef();
  const giftNameRef2 = useRef();
  const giftPriceRef2 = useRef();
  const giftStockRef2 = useRef();

  useEffect(async () => {
    message.destroy();
    // checkLoginState()
    const resp = await axios.get("http://localhost:8080/getGiftList")
    const data = await resp.data.data
    console.log(data);
    setOriginData(data)
    setGiftList(data)
    return () => {
    };
  }, []);
  const deleteGift = (record) => {
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: `确认要删除${record.name}吗?`,
      onOk() {
        //  删除礼物
        console.log(record.id);
        axios.post("http://localhost:8080/deleteGift?id=" + record.id).then(resp => {
          if (resp.data.state === "0") {
            message.success(resp.data.message, 1);
            setTimeout(() => {
              window.location.reload();
            }, 500);
          } else {
            message.error(resp.data.message, 1)
          }
        }).catch(err => {
          message.error("网络超时!", 1)
        })
      },
      onCancel() {
      },
    });
  }
  const photoupdate = (info) => {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }

  }

  const beforeUpload = (file) => {
    console.log(file.size);
    if (file.size > (2097152)) {
      console.log("图片超过2M");
      message.error(`图片不得超过2M`);
      return Upload.LIST_IGNORE;
    } else {
      return true;
    }
  }

  const columns = [
    {
      title: '礼品名称',
      dataIndex: 'name',
      width: '20%',
      align: 'center'
    },
    {
      title: '图片',
      dataIndex: 'photo',
      width: '20%',
      align: 'center',
      render: (text, record) => (
        <Popover placement="topLeft" content={'点击修改图片'}>
          <Upload maxCount={1} action={`http://localhost:8080/saveGiftPhoto?id=${record.id}`} beforeUpload={beforeUpload} onChange={photoupdate}>
            <Avatar shape="square" src={`http://localhost:8080/getGiftPhoto?id=${record.id}`} alt='礼物图片' size={100} />
          </Upload>
        </Popover>
      ),
    },
    {
      title: '价格',
      dataIndex: 'price',
      width: '20%',
      align: 'center'
    },
    {
      title: '库存',
      dataIndex: 'stock',
      width: '20%',
      align: 'center'
    },
    {
      title: 'Action',
      key: 'action',
      width: '15%',
      render: (text, record) => (
        <Space size="middle">
          <a onClick={() => { showModal(record) }}>编辑<EditTwoTone /></a>
          {/*  record 当前行的数据 */}
          <a onClick={() => { deleteGift(record) }} style={{ marginLeft: 5 }}> 删除<DeleteTwoTone twoToneColor="red" /></a>
        </Space>
      ),
    },
  ];

  const showModal = (record) => {
    setVisible(true);
    editGiftInfo.id = record.id;
    giftNameRef.current.state.value = '';
    giftPriceRef.current.state.value = '';
    giftStockRef.current.state.value = '';
  };

  const showModal2 = (record) => {
    setVisible2(true);
    editGiftInfo.id = record.id;
    giftNameRef.current.state.value = '';
    giftPriceRef.current.state.value = '';
    giftStockRef.current.state.value = '';
  };

  const handleOk = () => {
    editGiftInfo.name = giftNameRef.current.state.value || null;
    editGiftInfo.price = giftPriceRef.current.state.value || null;
    editGiftInfo.stock = giftStockRef.current.state.value || null;

    console.log("该礼物修改后信息:", editGiftInfo);

    axios.post("http://localhost:8080/editGift", editGiftInfo).then(resp => {
      if (resp.data.state === "0") {
        message.success(resp.data.message, 1)
        setVisible(false);
        setTimeout(() => {
          window.location.reload()
        }, 300);

      } else {
        message.error(resp.data.message, 1)
        setVisible(false);
      }

    }).catch(err => {
      message.error("请求超时!", 1);
    })

  };

  const handleOk2 = () => {
    addGiftInfo.name = giftNameRef2.current.state.value || null;
    addGiftInfo.price = giftPriceRef2.current.state.value || null;
    addGiftInfo.stock = giftStockRef2.current.state.value || null;

    console.log("新增的礼物信息:", addGiftInfo);

    axios.post("http://localhost:8080/addGift", addGiftInfo).then(resp => {
      if (resp.data.state === "0") {
        message.success(resp.data.message, 1)
        setVisible(false);
        setTimeout(() => {
          window.location.reload()
        }, 300);

      } else {
        message.error(resp.data.message, 1)
        setVisible(false);
        setTimeout(() => {
          window.location.reload()
        }, 300);
      }

    }).catch(err => {
      message.error("请求超时!", 1);
      setVisible(false);
    })

  };

  const handleCancel = () => {
    setVisible(false);
    editGiftInfo = {}
  };
  const handleCancel2 = () => {
    setVisible2(false);
    addGiftInfo = {}
  };
  const showAllNoPhotoGift = () => {
    axios.get("http://localhost:8080/getNoPhotoGiftList").then(resp => {
      if (resp.data.state === "0") {
        setOriginData(resp.data.data)
      } else {
        message.error(resp.data.message, 1)
      }
    }).catch(err => {
      console.log(err);
      message.error("请求失败!", 1)
    })
  }
  const renderTableHead = () => {
    return (
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span>礼物管理</span>
        <Space>
          <Search placeholder="礼物名称" onSearch={onSearch} allowClear style={{ width: 200 }} />
          <Button onClick={showModal2} type="primary" icon={<HeartTwoTone twoToneColor="#eb2f96" />}>添加礼物</Button>
          <Button onClick={showAllNoPhotoGift} type="primary" >无图片礼物</Button>
        </Space>
      </div>

    )
  }
  const onSearch = (value) => {
    console.log(value);
    let rs = [];
    rs = originData.filter((item, index) => {
      console.log(item);
      return item.name.indexOf(value) != -1
    })
    console.log(rs);
    setOriginData(rs)
    if (value == null || value == "") {
      setOriginData(giftList)
    }

  }
  return (
    <div className="animate__animated animate__fadeIn">
      <Table columns={columns} dataSource={originData} title={renderTableHead} pagination={{
        pageSize: 4,
      }} />
      <Modal
        title="编辑礼品信息"
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={'40%'}
        centered={true}
      >
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>礼品名称</span><Input style={{ width: screenWidth * 0.2 }} ref={giftNameRef} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>价格</span><Input type={`number`} style={{ width: screenWidth * 0.2 }} ref={giftPriceRef} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>库存</span><Input type={`number`} style={{ width: screenWidth * 0.2 }} ref={giftStockRef} /><br /></p>
      </Modal>

      <Modal
        title="添加礼品"
        visible={visible2}
        onOk={handleOk2}
        onCancel={handleCancel2}
        width={'40%'}
        centered={true}
      >
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>礼品名称</span><Input style={{ width: screenWidth * 0.2 }} ref={giftNameRef2} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>价格</span><Input type={`number`} style={{ width: screenWidth * 0.2 }} ref={giftPriceRef2} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>库存</span><Input type={`number`} style={{ width: screenWidth * 0.2 }} ref={giftStockRef2} /><br /></p>
      </Modal>
    </div>
  )

}
